import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/api/api_service.dart';
import 'package:flutter_app/me/register_page.dart';
import 'package:flutter_app/model/user_bean.dart';
import 'package:flutter_app/utils/constant.dart';
import 'package:flutter_app/utils/sp_util.dart';
import 'package:fluttertoast/fluttertoast.dart';

class LoginPage extends StatefulWidget {
  @override
  LoginPageState createState() => new LoginPageState();
}

class LoginPageState extends State<LoginPage> {
  final _userNameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isInputUserNameContent = false;
  bool _isInputPasswordContent = false;

  @override
  void initState() {
    _userNameController.addListener(() {
      setState(() {
        if (_userNameController.text.trim().isNotEmpty) {
          _isInputUserNameContent = true;
        } else {
          _isInputUserNameContent = false;
        }
      });
    });
    _passwordController.addListener(() {
      setState(() {
        if (_passwordController.text.trim().isNotEmpty) {
          _isInputPasswordContent = true;
        } else {
          _isInputPasswordContent = false;
        }
      });
    });
    super.initState();
  }

  void _login() async {
    var data = {
      "username": _userNameController.text,
      "password": _passwordController.text,
    };
    ApiService().login(data, (UserBean userBean) {
      if (userBean.errorCode == 0) {
        SpUtil().putString(Constant.usernameTag, _userNameController.text);
        SpUtil().putBool(Constant.isLoginKey, true);
        Fluttertoast.showToast(msg: "登入成功");
        print(SpUtil().getBool(Constant.isLoginKey));
        Navigator.pop(context, "loginSuccessful");
      } else {
        Fluttertoast.showToast(msg: userBean.errorMsg);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey,
        image: DecorationImage(
            image: AssetImage("images/landscape.jpg"),
            colorFilter: ColorFilter.mode(
                Colors.black.withOpacity(0.2), BlendMode.dstATop),
            fit: BoxFit.fill),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        resizeToAvoidBottomInset: false, //啥意思？
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.transparent,
          title: Text("登入账号"),
          centerTitle: true,
        ),
        body: Padding(
          padding: EdgeInsets.only(top: 50, right: 25, left: 25),
          child: Column(
            children: [
              TextField(
                controller: _userNameController,
                textInputAction: TextInputAction.go,
                keyboardType: TextInputType.text,
                decoration: InputDecoration(
                    labelText: "用户名",
                    hintText: "请输入用户名或邮箱",
                    prefixIcon: Icon(Icons.account_circle),
                    suffixIcon: Visibility(
                      child: IconButton(
                        icon: Icon(Icons.clear),
                        alignment: Alignment.bottomRight,
                        padding: EdgeInsets.all(1),
                        onPressed: () {},
                      ),
                      visible: _isInputUserNameContent,
                    )),
              ),
              TextField(
                controller: _passwordController,
                keyboardType: TextInputType.visiblePassword,
                decoration: InputDecoration(
                    labelText: "密码",
                    hintText: "请输入密码",
                    prefixIcon: Icon(Icons.lock),
                    suffixIcon: Visibility(
                      child: IconButton(
                        icon: Icon(Icons.clear),
                        alignment: Alignment.bottomCenter,
                        padding: EdgeInsets.all(1),
                        onPressed: () {},
                      ),
                      visible: _isInputPasswordContent,
                    )),
                obscureText: true,
              ),
              Padding(
                padding: EdgeInsets.only(top: 20),
                child: RaisedButton(
                  child: Text("登入"),
                  color: Colors.white54,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  onPressed: () {
                    if (_isInputUserNameContent && _isInputPasswordContent) {
                      _login();
                      FocusScope.of(context).unfocus();
                    } else if (!_isInputUserNameContent) {
                      Fluttertoast.showToast(msg: "请输入用户名");
                    } else if (!_isInputPasswordContent) {
                      Fluttertoast.showToast(msg: "请输入密码");
                    } else {
                      Fluttertoast.showToast(msg: "请输入账号密码");
                    }
                  },
                ),
              ),
              Expanded(
                  child: Container(
                alignment: Alignment.bottomCenter,
                margin: EdgeInsets.only(top: 25,bottom: 25),
                child: GestureDetector(
                  child: Text(
                    "还没注册？，点击注册",
                    style: TextStyle(
                        fontSize: 15,
                        color: Colors.white,
                        fontWeight: FontWeight.bold),
                  ),
                  onTap: (){
                    Navigator.push(context,MaterialPageRoute(builder: (context)=>RegisterPage()));
                  },
                ),
              ))
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _userNameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }
}
